import { Toast } from 'antd-mobile'
import { getUserInfo } from './login' 
import { reqGoodsInfo,reqCartAdd } from '../../request/api'
//初始状态
const initState = {
    goodsinfo: {},//单个商品信息
    visible: false,//弹窗是否显示
    num: 1,//数量
    arr: ['商品', '评价', '详情', '推荐']
}

// actionType
const TYPES = {
    DETAIL_CHANGE_GOODSINFO: 'DETAIL_CHANGE_GOODSINFO',
    DETAIL_CHANGE_VISIBLE: 'DETAIL_CHANGE_VISIBLE',
    DETAIL_CHANGE_NUM: 'DETAIL_CHANGE_NUM',

}

// reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.DETAIL_CHANGE_GOODSINFO:
            return {
                ...state,
                goodsinfo: action.goodsinfo
            }
        case TYPES.DETAIL_CHANGE_VISIBLE:
            return {
                ...state,
                visible: action.visible
            }
        case TYPES.DETAIL_CHANGE_NUM:
            return {
                ...state,
                num: action.num
            }
        default:
            return state;
    }
}

// actionCreators
export const actions = {
    changeGoodsinfo: (goodsinfo) => ({ type: TYPES.DETAIL_CHANGE_GOODSINFO, goodsinfo }),
    // 请求商品详情信息
    requestGoodsinfo: (id) => {
        return (dispatch, getState) => {
            reqGoodsInfo({id}).then(res=>{
                if(res.data.code==200){
                    dispatch(actions.changeGoodsinfo(res.data.list[0]))
                }
            })
        }
    },
    changeVisible: (visible) => ({ type: TYPES.DETAIL_CHANGE_VISIBLE, visible }),
    changeNum: (num) =>{
        return (dispatch,getState)=>{
            if(num<=1){
                Toast.show({
                    content:'至少加购1件'
                })
                return;
            }
            dispatch({ type: TYPES.DETAIL_CHANGE_NUM, num })
        }
    },
    // 加入购物车
    requestAddCart:(type)=>{
        return (dispatch,getState)=>{
            // 整理参数
            let userInfo=getUserInfo(getState());
            let goodsinfo=getGoodsinfo(getState());
            let num=getNum(getState());
            // 发请求
            reqCartAdd({
                uid:userInfo.uid,
                type,
                goodsid:goodsinfo.id,
                num
            }).then(res=>{
                if(res.data.code==200){
                    Toast.show({
                        content:res.data.msg
                    })
                    dispatch(actions.changeVisible(false))
                }
            })
        }
    }
}
// selectors
export const getGoodsinfo = state => state.detail.goodsinfo;
export const getVisible = state => state.detail.visible;
export const getNum = state => state.detail.num;
export const getArr = state => state.detail.arr;

export default reducer